<template>
  <div class="container">
    <!-- 通过v-for渲染多选框列表 -->
    <div class="check-container" v-for="(item, i) in data" :key="item.value">
      <label class="showLable" :for="item.value">
        <input type="checkbox" :id="item.value" :value="item.value" :checked="checked[i]" @change="updateValue(item.value, $event)" />
        {{ item.label }}
      </label>
    </div>
  </div>
</template>

<script>
export default {
  model: {
    prop: 'value2',
    event: 'change'
  },
  props: {
    data: {
      type: Array,
      default: () => []
    },
    value2: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      checkArr: [],
      checked: []
    };
  },
  created() {

  },
  methods: {
    initChecked() {
      this.checkArr = this.value2.split(' ').map(Number);
      for (let i = 0; i < this.data.length; i++) {
        let res = this.checkArr.filter(item => item === this.data[i].value);
        this.$set(this.checked, i, res.length);
      }
    },
    updateValue(v, e) {
      if (e.target.checked) {
        this.checkArr.push(v);
      } else {
        // 取消选择的情况
        this.checkArr = this.checkArr.filter(item => item !== v);
      }
      this.$emit('change', this.checkArr.join(' '));
    }
  },
  watch: {
    value2: function() {
      this.initChecked();
    }
  }
};
</script>

<style lang="scss" scoped>
.check-container {
  margin: 10px 15px;
}
.showLable {
  margin-left: 5px;
}
</style>
